<template>
  <div class="supervise-monitor">
    <div class="main-nav">
      <div class="nav-container"
           v-for="navKey in navMenuKeyList"
           :key="navKey">
        <div class="nav-header"
             @click="expandNav(navKey)">
          <i class="syIcon sy-arrow-right"
             :class="{
              'sy-arrow-down': expandKey === navKey
            }"></i>
          <span class="nav-title">
            {{ getNavTitle(navKey) }}
          </span>
          <i class="syIcon sy-plus-line"
             style="color: #999"
             @click.stop="addSupervise(navKey)"></i>
        </div>
        <template v-if="navMenuMap && navMenuMap[navKey]">
          <div class="nav-item"
               v-show="expandKey === navKey"
               @click="goToNav(item, navKey)"
               :class="{
              active: activeId === item.id
            }"
               v-for="item in navMenuMap[navKey]"
               :key="item.id">
            <div class="nav-item-title"
                 :title="item.boardName">
              <div class="label">
                <span> {{ item.boardName }}</span>
              </div>

              <div v-if="item.canModify || item.canDelete"
                   class="operate">
                <span :title="$i18n('common.operate.edit')"
                      class="xicon-editor operate-text"
                      @click.stop="modifyBoard(item)"></span>
                <span :title="$i18n('common.button.delete.label')"
                      class="xicon-delete operate-text"
                      @click.stop="deleteBoard(item)"></span>
              </div>
            </div>
          </div>
        </template>
      </div>
    </div>
    <div class="main-content">
      <iframe class="superviseIframe"
              ref="iframe"
              :src="iframeSrc"
              frameborder="0"></iframe>
    </div>
  </div>
</template>

<script>
  import { getParams } from '../../utils';
  import { formatRequestDataToJSON } from '@/utils/api';
  import * as Fiber from 'fiber';
  export default {
    name: 'SuperviseMonitor',
    components: {},
    data() {
      return {
        iframeSrc: '',
        navMenuKeyList: ['mySupervise', 'deptAdmin', 'formAdmin'],
        navMenuMap: null,
        expandKey: 'mySupervise',
        activeId: '1',
        isExecuteClick: true
      };
    },
    created() {
      this.navTitleTextMap = {
        mySupervise: this.$i18n('supervise.my.supervise'),
        formAdmin: this.$i18n('supervise.my.manager.template'),
        deptAdmin: this.$i18n('supervise.my.dept')
      };
      this.urlParamObj = getParams(window.location.search);
      this.getMenuAuthority();
      this.getNavData();
    },
    methods: {
      initDefaultMenu(menuId) {
        let { quotaManagerType } = this.urlParamObj;
        let expandKey = this.expandKey;
        let activeMenu = this.activeMenu;
        let quotaType = this.quotaType;

        if ('deptAdmin' == quotaManagerType) {
          this.expandKey = 'deptAdmin';
          this.activeMenu = this.navMenuMap.deptAdmin[0];
        } else if ('formAdmin' == quotaManagerType) {
          this.expandKey = 'formAdmin';
          this.activeMenu = this.navMenuMap.formAdmin[0];
        } else if ('workflowProblem' == quotaManagerType) {
          this.quotaType = 'processException';
          this.expandKey = 'mySupervise';
          this.activeMenu = this.navMenuMap.mySupervise[0];
        } else {
          this.expandKey = 'mySupervise';
          this.activeMenu = this.navMenuMap.mySupervise[0];
        }

        this.activeId = this.activeMenu.id;
        if (menuId) {
          this.expandKey = expandKey;
          this.quotaType = quotaType;
          this.activeMenu = activeMenu;
        }
        this.goToNav(this.activeMenu, this.expandKey);
      },
      getNavData(stopReload = false, menuId) {
        let sendParams = {};
        const args = `managerMethod=getSuperviseBoardSetting&arguments=${formatRequestDataToJSON(
          sendParams
        )}`;
        const url = `${window.window._ctxPath}/ajax.do?method=ajaxAction&managerName=superviseManager`;
        window.axios
          .post(url, args, {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
            }
          })
          .then((data) => {
            const result = data.data;
            if (result) {
              this.navMenuMap = result;
              if (!stopReload) {
                this.initDefaultMenu(menuId);
              }
            }
          });
      },
      getNavTitle(key) {
        return this.navTitleTextMap[key];
      },
      // 获取菜单显示权限
      getMenuAuthority() {
        const url = `${window.window._ctxPath}/rest/coll/supervise/user/auth`;
        window.axios.get(url).then((data) => {
          const result = data.data;
          if (result && result.data) {
            const data = result.data;
            const newNavMenuKeyList = [];
            if (data.hasSupervise) {
              newNavMenuKeyList.push('mySupervise');
            }
            if (data.deptAdmin) {
              newNavMenuKeyList.push('deptAdmin');
            }
            if (data.formAdmin) {
              newNavMenuKeyList.push('formAdmin');
            }

            this.navMenuKeyList = newNavMenuKeyList;
          }
        });
      },
      expandNav(navKey) {
        this.expandKey = navKey;
      },
      addSupervise(managerType) {
        this.showSetting(managerType, 'add', '');
      },
      modifyBoard(obj) {
        let id = obj.id;
        this.showSetting(null, 'modify', id);
      },
      goToNav(menu, navKey) {
        this.activeId = menu.id;
        this.activeMenu = menu;
        let { quotaType, srcFrom, templeteIds } = this.urlParamObj;
        let urlParms = {
          method: 'myManagerSupervise',
          quotaType: this.quotaType || quotaType,
          srcFrom,
          templeteIds,
          managerType: navKey
        };
        if (menu.member) {
          let memberMsg = encodeURIComponent('Member|' + menu.id);
          Object.assign(urlParms, {
            managerType: 'deptAdmin',
            memberId: memberMsg
          });
        } else {
          Object.assign(urlParms, {
            boardId: menu.id
          });
        }
        let url = '';

        if (process.env.NODE_ENV === 'development') {
          // 开发地址
          const urlMap = {
            mySupervise: '/supervise-mine.html',
            deptAdmin: '/supervise-dept.html',
            formAdmin: '/supervise-admin.html'
          };
          url = this.mergeUrlParams(urlMap[navKey], urlParms);
        } else {
          const urlMap = {
            mySupervise:
              window._ctxPath + '/apps_res/collaboration/supervise/supervise-mine/index.html',
            deptAdmin:
              window._ctxPath + '/apps_res/collaboration/supervise/supervise-dept/index.html',
            formAdmin:
              window._ctxPath + '/apps_res/collaboration/supervise/supervise-admin/index.html'
          };
          url = this.mergeUrlParams(urlMap[navKey], urlParms);
        }

        let curUrl = url + window.getCtpTop().CsrfGuard.getUrlSurffix();
        if (this.iframeSrc === curUrl) {
          this.$refs.iframe.contentWindow.location.reload();
        } else {
          this.iframeSrc = curUrl;
        }
      },
      showSetting(managerType, type, id) {
        const _this = this;
        var dialog = $.dialog({
          targetWindow: window.getCtpTop(),
          id: 'superviseBoardSetting',
          url:
            window._ctxPath +
            '/supervise/supervise.do?method=superviseBoardSetting&managerType=' +
            managerType +
            '&boardId=' +
            id,
          width: 520,
          height: 290,
          title: $.i18n('supervise.board.title'),
          // 个人督办看板
          buttons: [
            {
              text: $.i18n('common.button.ok.label'),
              // 确定
              handler: function handler() {
                var rv = dialog.getReturnValue();

                if (rv == 'error') {
                  return;
                } //保存看板信息
                if(_this.isExecuteClick){
                  _this.isExecuteClick = false;
                  var msg = callBackendMethod('superviseManager', 'addSuperviseBoardSetting', rv, {
                    success: function success(rs) {
                      if (rs && rs.msg != '') {
                        $.alert(rs.msg);
                      } else {
                        if (type !== 'add') {
                          if (_this.activeId === id) {
                            _this.getNavData(false, id);
                          } else {
                            _this.getNavData(true);
                          }
                        } else {
                          _this.getNavData(true);
                        }

                        dialog.close();
                      }
                      _this.isExecuteClick = true;
                    },
                    error: function error(request, settings, e) {
                      $.alert(e);
                    }
                  });
                }
              }
            },
            {
              text: $.i18n('common.button.cancel.label'),
              // 取消
              handler: function handler() {
                dialog.close();
              }
            }
          ]
        });
      },
      deleteBoard(obj) {
        let id = obj.id;
        const _this = this;
        $.confirm({
          // 该操作不能恢复，是否进行删除操作
          msg: $.i18n('collaboration.confirmDelete'),
          ok_fn: function ok_fn() {
            callBackendMethod('superviseManager', 'deleteBoard', id, {
              success: function success(flag) {
                if ('success' == flag) {
                  if (_this.activeId === id) {
                    _this.getNavData();
                  } else {
                    _this.getNavData(true);
                  }
                  Fiber.message.success($.i18n('common.delete.success.label'));
                } else {
                  $.alert(flag);
                }
              },
              error: function error(request, settings, e) {
                $.alert(e);
              }
            });
          }
        });
      },

      mergeUrlParams(url, params) {
        const paramsKeys = Object.keys(params);
        paramsKeys.forEach((key, index) => {
          if (params[key] !== undefined) {
            if (index === 0) {
              url += '?';
              url += `${key}=${params[key]}`;
            } else {
              url += `&${key}=${params[key]}`;
            }
          }
        });
        return url;
      }
    },
    mounted() {}
  };
</script>

<style>
  @import url('../../assets/css/common.css');
</style>
<style lang="scss">
  .supervise-monitor {
    height: 100%;
    width: 100%;
    display: flex;
    * {
      box-sizing: border-box;
    }
    .main-nav {
      width: 200px;
      border-right: 1px solid #eceff6;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      font-size: 14px;
      overflow: auto;
      .nav-header {
        display: flex;
        height: 44px;
        align-items: center;
        color: #111111;
        padding: 0 20px;
        cursor: pointer;
        background-color: #f9fafc;
        &:hover {
          // background-color: #f9fafc;
          // background-color: var(--theme-brand4, #f9fafc);
          background-color: #f0f6ff;
          background-color: var(--theme-brand1, #f0f6ff);
        }
        // border-bottom: 1px solid #e4e7ed;
        .nav-title {
          flex: 1;
          padding: 0 8px;
          overflow: hidden;
          text-overflow: ellipsis;
          word-break: keep-all;
          white-space: nowrap;
        }
        .syIcon {
          font-size: 14px;
        }
      }
      .nav-item {
        cursor: pointer;
        padding: 0 20px;
        padding-left: 40px;
        height: 44px;
        display: flex;
        align-items: center;
        color: #111111;

        &:hover {
          background-color: #e6f6ff;
          background-color: var(--theme-brand1, #e6f6ff);
          .nav-item-title {
            .operate {
              display: block;
            }
          }
        }
        .nav-item-title {
          display: flex;
          width: 100%;
          height: 24px;
          .label {
            overflow: hidden;
            text-overflow: ellipsis;
            word-break: keep-all;
            white-space: nowrap;
            flex: 1;
            justify-content: space-between;
            font-size: 14px;
          }
          .operate {
            display: none;
          }
          .operate-text {
            font-size: 14px;
            color: #315cfa;
            color: var(--theme-brand6, #315cfa);
          }
          .operate-text + .operate-text {
            margin-left: 8px;
          }
        }
      }

      .nav-item.active {
        position: relative;
        background-color: var(--theme-brand1, #e6f6ff);

        &::after {
          content: '';
          position: absolute;
          left: 0;
          top: 0;
          height: 100%;
          width: 4px;
          background-color: var(--theme-brand4, #4a9ff2);
        }
      }
    }
    .main-content {
      flex: 1;
      overflow: hidden;
      position: relative;

      .superviseIframe {
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        height: 100%;
        width: 100%;
        margin: 0;
        padding: 0;
      }
    }
  }
</style>
